# -*- coding:utf-8 -*-
import socket
import zipfile
import os
import datetime
import shutil

import config


server = socket.socket()
server.bind((config.testdata_syncer_host, config.testdata_syncer_port))
print("[%s] 数据同步开始监听%s:%s" % (datetime.datetime.now(), config.testdata_syncer_host, str(config.testdata_syncer_port)))
server.listen(5)

while True:
    conn, address = server.accept()
    print("[%s] 连接接入%s" % (datetime.datetime.now(), conn))
    task = conn.recv(1024).decode()
    if task.find("del") == 0:
        print("[%s] 接收到删除题目数据任务 #%s" % (datetime.datetime.now(), task.split(",")[1]))
        try:
            shutil.rmtree(config.test_data_dir + "/" + str(task.split(",")[1]))
        except:
            print("[%s] 未找到题目数据#%s" % (datetime.datetime.now(), task.split(",")[1]))
        else:
            print("[%s] 删除题目数据#%s 成功" % (datetime.datetime.now(), task.split(",")[1]))
    else:
        print("[%s] 接收到上传题目数据任务" % (datetime.datetime.now()))
        f = open(config.test_data_dir + "temp.zip", "wb")
        while True:
            data = conn.recv(1024)
            if not data:
                break
            f.write(data)
        f.close()
        print("[%s] 接收完毕" % (datetime.datetime.now()))
        zipf = zipfile.ZipFile(config.test_data_dir + "temp.zip")
        zipf.extractall(config.test_data_dir)
        os.remove(config.test_data_dir + "temp.zip")
        print("[%s] 数据包解压完毕" % (datetime.datetime.now()))
